<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | Bigotry <3162875@qq.com>                               |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\api\logic;



use app\common\model\EthAccount;
use app\common\model\EthAccountLog;
use app\common\model\GamesLog;
use app\common\model\UserAccount;
use app\common\model\UserAccountLog;
use app\common\model\UserSms;
use app\common\model\Wallet;
use app\common\model\WithdrawalPayinfo;
use think\Db;

/**
 * 用户接口逻辑
 */
class Gap extends ApiBase
{
    

    
    /**
     * 币币账户列表
     */
    public function currency_account($data = [])
    {
        $uid=$this->logicApiBase->member['id'];
        $where=['is_currency'=>1,'status'=>1,'is_virtual'=>1];
        if(!empty($data['search_data'])){
            $where['name']=['like','%'.$data['search_data'].'%'];
        }

        UserAccount::checkWallet($uid);
        $list=Wallet::field('id,name,parities,usdt_price')->where($where)->select();
        //$list=UserAccount::field('id,balance,wallet_id')->where($where)->select();
        $alltotal=$usdt=0;
        foreach ($list as $k=>$v){

            $account=UserAccount::get(['user_id'=>$uid,'wallet_id'=>$v['id']]);
            $list[$k]['balance']=$account->balance;
            $list[$k]['total_money']=($account->balance+$account->freeze_balance)*$v['parities'];
            $list[$k]['freeze_balance']=$account->freeze_balance;
            $list[$k]['usdt_total']=format_money($v['usdt_price']*($account->balance+$account->freeze_balance));
            $usdt+=($account->balance+$account->freeze_balance)*$v['usdt_price'];
            $alltotal+=($account->balance+$account->freeze_balance)*$v['parities'];


        }

       return ['alltotal'=>format_money($alltotal),'usdt'=>format_money($usdt),'list'=>$list];


    }


    /***
     * 用户充币地址接口
     *
     *
     */
    public function get_address($data){
        $uid=$this->logicApiBase->member['id'];
        return $this->modelUserAccount->where(['user_id'=>$uid,'wallet_id'=>$data['wallet_id']])->value('blockchain_address2');
    }

    /**
     * 法币账户列表
     */
    public function french_currency_account($data = [])
    {
        $uid=$this->logicApiBase->member['id'];
        $where=['is_currency'=>1,'status'=>1,'is_virtual'=>1];
        if(!empty($data['search_data'])){
            $where['name']=['like','%'.$data['search_data'].'%'];
        }

        UserAccount::checkWallet($uid);
        $list=Wallet::field('id,symbol,name,usdt_price,parities')->where($where)->select();
        $account=EthAccount::get(['user_id'=>$uid]);
        $alltotal=$usdt=0;
        foreach ($list as $k=>$v){
            $symbol=$v->symbol.'_do';
            $symbol_lock=$v->symbol.'_lock';
            $list[$k]['balance']=$account->$symbol;
            $list[$k]['total_money']=format_money(($account->$symbol+$account->$symbol_lock)*$v['parities']);
            $list[$k]['freeze_balance']=$account->$symbol_lock;
            $list[$k]['usdt_total']=$v['usdt_price']*$account->$symbol;
            $usdt+=($account->$symbol+$account->$symbol_lock)*$v['usdt_price'];
            $alltotal+=($account->$symbol+$account->$symbol_lock)*$v['parities'];

        }

        return ['alltotal'=>format_money($alltotal),'usdt'=>format_money($usdt),'list'=>$list];


    }


    /**
     * 法币账户财务记录
     */
    public function french_currency_account_log($data = [])
    {
        $uid=$this->logicApiBase->member['id'];
        $where['wallet_id']=$data['wallet_id'];
        if(!empty($data['type'])){
            $where['type']=$data['type'];
        }
        $wallet=$this->modelWallet->getInfo(['id'=>$data['wallet_id']]);
        if(!$wallet){
            return ajaxreturn(1,lang('wallet_id 参数错误'));
        }
        $eth_account=EthAccount::get(['user_id'=>$uid]);
        $where['user_id']=$uid;
        $list=$this->modelEthAccountLog->getList($where,'id,serial_number,number,user_id,create_time,remark,wallet_id,is_add','id desc');

        return ['balance'=>$eth_account[$wallet['symbol'].'_do'],'total_money'=>format_money(($eth_account[$wallet['symbol'].'_do']+$eth_account[$wallet['symbol'].'_lock'])*$wallet['parities']),'freeze_balance'=>$eth_account[$wallet['symbol'].'_lock'],'list'=>$list];


    }

    /**
     * 币币账户财务记录
     */
    public function currency_account_log($data = [])
    {
        $uid=$this->logicApiBase->member['id'];
        $where['wallet_id']=$data['wallet_id'];
        $wallet=$this->modelWallet->getInfo(['id'=>$data['wallet_id']]);
        if(!$wallet){
            return ajaxreturn(1,lang('wallet_id 参数错误'));
        }
        $account=UserAccount::get(['user_id'=>$uid,'wallet_id'=>$data['wallet_id']]);
        $where['user_id']=$uid;
        if(!empty($data['type'])){

            $where['type']=$data['type'];
        }
        $list=$this->modelUserAccountLog->getList($where,'id,serial_number,number,user_id,remark,create_time,wallet_id,is_add','id desc');
//        $list=$this->modelTransferCurrency->getList($where,'id,number,user_id,uid,create_time','id desc');
        return ['balance'=>$account['balance'],'total_money'=>format_money(($account['balance']+$account['freeze_balance'])*$wallet['parities']),'freeze_balance'=>$account['freeze_balance'],'list'=>$list];
    }


    /**
     * 币币划分到法币账户
     */
    public function currency_to_french_currency($data = [])
    {
        $uid=$this->logicApiBase->member['id'];
        if($this->logicApiBase->member['is_trans']==0){
            return ajaxreturn(1,lang('区块确认网络异常，无法完成划转'));
        }
        if(empty($data['number']) || !is_numeric($data['number']) || $data['number']<0){
            return ajaxreturn(1,lang('请输入数量'));
        }

        $wallet=$this->modelWallet->getInfo(['id'=>$data['wallet_id']]);
        if(!$wallet){
            return ajaxreturn(1,lang('wallet_id 参数错误'));
        }

        //是否开启划转
        if($wallet['is_paddle']!=1){
            return ajaxreturn(1,lang('暂未开启'));
        }
        $exchange_min=(int)$wallet['paddle_min'];
        $exchange_max=(int)$wallet['paddle_max'];
        if($exchange_min){
            if($exchange_min>$data['number']){
                return ajaxreturn(1,lang('数量最小为').$exchange_min);
            }

        }
        if($exchange_max){
            if($exchange_max<$data['number']){
                return ajaxreturn(1,lang('数量最大为').$exchange_max);
            }

        }
        if(!empty($wallet['paddle_mult'])){
            if($data['number']%$wallet['paddle_mult']!=0){
                return ajaxreturn(1,lang('数量必须为').$wallet['paddle_mult'].lang('的倍数'));
            }

        }

        $poundage_number=$data['number']*$wallet['paddle_poundage']/100;
        $result=$this->check_password($data['pin_password']);
        switch ($result)
        {
            case 1:
                return  ajaxreturn(1,lang('您的账户操作多次密码验证不正确，如果不是您本人操作，请前往修改密码'));
                break;
            case 2:
                return  ajaxreturn(1,lang('您的密码验证错误2次，您的账户为了账户安全，已被冻结，请在30分钟后再次尝试。'));

                break;
            case 3:
                return  ajaxreturn(1,lang('您的密码验证错误1次，您还可以尝试1次！'));
                break;


        }

        Db::startTrans();
        $account=UserAccount::check(['wallet_id'=>$wallet['id'],'user_id'=>$uid],false);
        if($data['number']>$account['balance']){
            return ajaxreturn(1,lang('钱包余额不足'));
        }

        try{
            //扣除用户钱包余额
            $account->balance-=$data['number'];
            $account->save();

            //写入资金流水
            UserAccountLog::create([
                'user_id'=>$uid,
                'number'=>$data['number'],
                'wallet_id'=>$wallet['id'],
                'before_blance'=>$account->balance+$data['number'],
                'after_blance'=>$account->balance,
                'poundage_number'=>$poundage_number,
                'is_add'=>2,
                'remark'=> '从币币账户转入法币账户',
                'type'=>20
            ]);


            //法币账户增加
            $symbol=$wallet['symbol'].'_do';
            $eth_account=EthAccount::where(['user_id'=>$uid])->lock(true)->find();
            $eth_account->$symbol+=$data['number']-$poundage_number;
            $eth_account->save();
            //写入资金流水
            EthAccountLog::create([
                'user_id'=>$uid,
                'number'=>$data['number'],
                'wallet_id'=>$wallet['id'],
                'before_blance'=>$eth_account->$symbol-$data['number']+$poundage_number,
                'after_blance'=>$eth_account->$symbol,
                'remark'=> '从币币账户转入法币账户',
                'poundage_number'=>$poundage_number,
                'is_add'=>1,
                'type'=>1
            ]);
            //写入划转记录
            $data['user_id']=$uid;
            $data['form_wallet_id']=$wallet['id'];
            $data['to_wallet_id']=$wallet['id'];
            $data['remark']='1个'.$wallet['name'].'/'.$wallet['parities'].'￥';
            $data['type']=16;
            $data['state']=1;
            $this->modelTransfer->setInfo($data);
            Db::commit();
            return ajaxreturn(0,lang('成功'));
        }catch (\Exception $e){
            Db::rollback();
            return ajaxreturn(0,$e->getMessage());
            return ajaxreturn(1,lang('服务器繁忙,请稍后再试'));
        }


    }



    /**
     * 法币划分到币币账户
     */
    public function french_currency_to_currency($data = [])
    {
        $uid=$this->logicApiBase->member['id'];
        if($this->logicApiBase->member['is_trans']==0){
            return ajaxreturn(1,lang('区块确认网络异常,无法完成划转'));
        }

        if(empty($data['number']) || !is_numeric($data['number']) || $data['number']<0){
            return ajaxreturn(1,lang('请输入数量'));
        }
        $result=$this->check_password($data['pin_password']);
        switch ($result)
        {
            case 1:
                return  ajaxreturn(1,lang('您的账户操作多次密码验证不正确，如果不是您本人操作，请前往修改密码'));
                break;
            case 2:
                return  ajaxreturn(1,lang('您的密码验证错误2次，您的账户为了账户安全，已被冻结，请在30分钟后再次尝试。'));

                break;
            case 3:
                return  ajaxreturn(1,lang('您的密码验证错误1次，您还可以尝试1次！'));
                break;


        }
        $wallet=$this->modelWallet->getInfo(['id'=>$data['wallet_id']]);
        if(!$wallet){
            return ajaxreturn(1,lang('账户不存在'));
        }


        //是否开启划转
        if($wallet['is_paddle']!=1){
            return ajaxreturn(1,lang('暂未开启'));
        }
        $exchange_min=(int)$wallet['paddle_min'];
        $exchange_max=(int)$wallet['paddle_max'];
        if($exchange_min){
            if($exchange_min>$data['number']){
                return ajaxreturn(1,lang('数量最小为').$exchange_min);
            }

        }
        if($exchange_max){
            if($exchange_max<$data['number']){
                return ajaxreturn(1,lang('数量最大为').$exchange_max);
            }

        }
        if(!empty($wallet['paddle_mult'])){
            if($data['number']%$wallet['paddle_mult']!=0){
                return ajaxreturn(1,lang('数量必须为').$wallet['paddle_mult'].lang('的倍数'));
            }

        }

        $symbol=$wallet['symbol'].'_do';
        $poundage_number=$data['number']*$wallet['paddle_poundage']/100;

        Db::startTrans();
        $eth_account=EthAccount::where(['user_id'=>$uid])->lock(true)->find();

        if($data['number']>$eth_account->$symbol){
            return ajaxreturn(1,lang('钱包余额不足'));
        }

        try{
            $account=UserAccount::check(['wallet_id'=>$wallet['id'],'user_id'=>$uid],false);
            //增加币币用户钱包余额
            $account->balance+=$data['number']-$poundage_number;
            $account->save();

            //写入资金流水
            UserAccountLog::create([
                'user_id'=>$uid,
                'number'=>$data['number'],
                'wallet_id'=>$wallet['id'],
                'before_blance'=>$account->balance-$data['number']+$poundage_number,
                'after_blance'=>$account->balance,
                'is_add'=>1,
                'poundage_number'=>$poundage_number,
                'remark'=> '从法币账户转入币币账户',
                'type'=>20
            ]);

            //法币账户减少


            $eth_account->$symbol-=$data['number'];
            $eth_account->save();
            //写入资金流水
            EthAccountLog::create([
                'user_id'=>$uid,
                'number'=>$data['number'],
                'wallet_id'=>$wallet['id'],
                'before_blance'=>$eth_account->$symbol+$data['number'],
                'after_blance'=>$eth_account->$symbol,
                'poundage_number'=>$poundage_number,
                'remark'=> '从法币账户转入币币账户',
                'is_add'=>2,
                'type'=>1
            ]);
            //写入划转记录
            $data['user_id']=$uid;
            $data['form_wallet_id']=$wallet['id'];
            $data['to_wallet_id']=$wallet['id'];
            $data['remark']='1个'.$wallet['name'].'/'.$wallet['parities'].'￥';
            $data['type']=17;
            $data['state']=1;
            $this->modelTransfer->setInfo($data);
            Db::commit();
            return ajaxreturn(0,lang('成功'));
        }catch (\Exception $e){
            Db::rollback();
            return ajaxreturn(0,$e->getMessage());
            return ajaxreturn(1,lang('服务器繁忙,请稍后再试'));
        }


    }




    /**
     * 总包提现
     */
    public function wallet_withdrawal($data = [])
    {
        $uid=$this->logicApiBase->member['id'];
        $member=$this->logicApiBase->member;
        $wallet_info=Wallet::get(1);
        if(!$wallet_info['is_withdrwal']){
            return  ajaxreturn(1,lang('服务暂未开启'));
        }
        //        //验证支付密码
        $result=$this->check_password($data['pin_password']);
        switch ($result)
        {
            case 1:
                return  ajaxreturn(1,lang('您的账户操作多次密码验证不正确，如果不是您本人操作，请前往修改密码'));
                break;
            case 2:
                return  ajaxreturn(1,lang('您的密码验证错误2次，您的账户为了账户安全，已被冻结，请在30分钟后再次尝试。'));

                break;
            case 3:
                return  ajaxreturn(1,lang('您的密码验证错误1次，您还可以尝试1次！'));
                break;


        }
        // include_once(ROOT_PATH . 'extend/GoogleAuthenticator/PHPGangsta/GoogleAuthenticator.php');
        // $ga = new \PHPGangsta_GoogleAuthenticator();
        // $checkResult = $ga->verifyCode($this->param['secret'], $this->param['auth_code'], 1); 
        if(empty($data['money']) || !is_numeric($data['money']) || $data['money']<0){
            return ajaxreturn(1,lang('请输入数量'));
        }
        if(empty($data['pay_type'])){
            return ajaxreturn(1,lang('请选择提现方式'));
        }

        //是否开启提现
        if($wallet_info['is_withdrwal']!=1){
            return ajaxreturn(1,lang('暂未开启'));
        }
        $exchange_min=(int)$wallet_info['withdrwal_min'];
        $exchange_max=(int)$wallet_info['withdrwal_max'];
        if($exchange_min>0){
            if($wallet_info['withdrwal_min']>$data['money']){
                return ajaxreturn(1,lang('提现最小金额为').$wallet_info['withdrwal_min']);
            }

        }
        if($exchange_max>0){
            if($exchange_max<$data['money']){
                return ajaxreturn(1,lang('提现最大金额为').$exchange_max);
            }

        }
        if(!empty($wallet_info['withdrwal_mult'])){
            if($data['money']%$wallet_info['withdrwal_mult']!=0){
                return ajaxreturn(1,lang('提现金额必须为').$wallet_info['withdrwal_mult'].lang('的倍数'));
            }

        }

        if(!empty($wallet_info['withdrwal_time'])){
            $arr=explode('~',$wallet_info['withdrwal_time']);
            $start_time=strtotime(date('Y-m-d').' '.$arr[0]);
            $end_time=strtotime(date('Y-m-d').' '.$arr[1]);
            $time=time();
            if($start_time>$time || $end_time<$time){
                return ajaxreturn(1,lang('开放时间为').$wallet_info['withdrwal_time']);
            }

        }
        if(!empty($data['email_type'])){
            if($data['email_type']==1){
                $user_sms_bean = $this->modelUserEmailLog->where(array('token' => $data['token'], 'email' => $this->logicApiBase->member['user_email'],'code'=>$data['code'], 'status' => 0))->find();
                if (empty($user_sms_bean)) {
                    return ajaxreturn(1, lang('验证码错误'));
    
                }
            }else{
                if(!$this->logicApiBase->member['google_open']){
                    return ajaxreturn(1, lang('谷歌验证已关闭'));
                }else{
                    include_once(ROOT_PATH . 'extend/GoogleAuthenticator/PHPGangsta/GoogleAuthenticator.php');
                    $ga = new \PHPGangsta_GoogleAuthenticator();
                    $checkResult = $ga->verifyCode($this->logicApiBase->member['google_auth'], $data['code'], 1);
                    if (!$checkResult) {
                        return ajaxreturn(1, lang('验证码错误'));
                    }
                }
 
            }
           
        }else{
            $data['area']=$this->logicApiBase->member['area'];
            $data['mobile']=$this->logicApiBase->member['mobile'];
            $res=$this->check_mobile_code($data);
            if(!$res){
                return ajaxreturn(1, lang('验证码错误'));
            }
        }


        $wallet=$this->modelUserPayType->getList(['type'=>['in',explode(',',$data['pay_type'])],'user_id'=>$uid,'status'=>1],'*','type asc',false);
        if(!$wallet){
            return ajaxreturn(1,lang('收款方式不存在'));
        }
        $arrs=[];
        foreach ($wallet as $k=>$v){
            $v['image']=$v->image;
            $arrs[]=$v;
        }
        $data['pay_json']=json_encode($arrs);
        $cc_number=$data['money'];

        Db::startTrans();
        $account=UserAccount::check(['wallet_id'=>1,'user_id'=>$uid],false);

        //游戏的业务流水为金额1倍不需要手续费
        if($data['money']<=$this->logicApiBase->member['bets_total_balance']){
            // $poundage=0;
            $poundage=0;
            $this->logicApiBase->member['bets_total_balance']-=$data['money'];
            
        }else{
//            $withdrwal_poundage=Wallet::where(['id'=>1])->value('withdrwal_poundage');
            // $poundage=getConfig('total_poundage_number');
            if(Db::name("user_account_log")->where(["user_id"=>$uid,"type"=>["in",[10,11,12]]])->sum("number")>0){
                $poundage=0;
                $this->logicApiBase->member['bets_total_balance']-=$data['money']; 
            }else{
                $poundage=$wallet_info['withdrwal_poundage'];
                $data['poundage_remark']='委托交易流水免手续费额度不足扣手续费';
            }
           
        }

        $data['poundage_number']=$poundage*$cc_number/100;
        $data['number']=$cc_number-$data['poundage_number'];
        if($data['money']+$data['poundage_number']>$account->balance){
            return ajaxreturn(1,lang('总包余额不足'));
        }

        try{
            
            //减少总钱包余额
            $account->balance-=$data['money']+$data['poundage_number'];
            $account->save();
            $this->logicApiBase->member->save();

            //写入订单记录
            $data['type']=3;
            $data['user_id']=$uid;

            $transfer_id = $this->modelTransfer->setInfo($data);

            //写入资金流水
            UserAccountLog::create([
                'user_id'=>$uid,
                'number'=>$data['money'],
                'wallet_id'=>$account['wallet_id'],
                'before_blance'=>$account->balance+$data['money']+$data['poundage_number'],
                'after_blance'=>$account->balance+$data['poundage_number'],
                'is_add'=>2,
                'remark'=> '线下提现',
                'type'=>5,
                'transfer_id'=>$transfer_id
            ]);
            //手续费写入流水
            if($data['poundage_number']>0){
                UserAccountLog::create([
                    'user_id'=>$uid,
                    'number'=>$data['poundage_number'],
                    'wallet_id'=>$account['wallet_id'],
                    'before_blance'=>$account->balance+$data['poundage_number'],
                    'after_blance'=>$account->balance,
                    'is_add'=>2,
                    'remark'=> '业务流水不足两倍扣除提现手续费:'.$data['poundage_number'],
                    'type'=>5,
                    'transfer_id'=>$transfer_id
                ]);
            }

            
//            WithdrawalPayinfo::create([
//                'user_id'=>$uid,
//                'withdrawal_id'=>$result,
//                'true_name'=>$wallet['true_name'],
//                'cover_id'=>$wallet['cover_id'],
//                'type'=>$wallet['type'],
//                'wallet_address'=>$wallet['wallet_address'],
//                'wallet_id'=>$wallet['wallet_id'],
//                'bank_card'=>$wallet['bank_card'],
//                'opening_bank'=>$wallet['opening_bank'],
//                'bank_address'=>$wallet['bank_address'],
//            ]);


            $mobile=getConfig('check_notice_mobile');
            $content= '您有一笔提现订单需正在审核中等待您处理';
            $data = [
                'mobile' =>$mobile,
                'content' => $content,
                'create_time' => TIME_NOW,
                'sms_type' => 30,
                'type' => 0,
                'area'=>86
            ];
            $sms=UserSms::create($data);

            if(getConfig('sms_is_test')!=1){
                $state=send_sms($mobile,$content ,config('settings'),86);
                if($state){
                    UserSms::where(['id'=>$sms->id])->update(['state'=>2]);
                }
            }
            Db::commit();

            return ajaxreturn(0,lang('您的提现请求已收到，等待审核状态，请注意查收'));
        }catch (\Exception $e){
            Db::rollback();
            return ajaxreturn(1,$e->getMessage());
            return ajaxreturn(1,lang('服务器繁忙,请稍后再试'));
        }


    }


    /***
     * 币币互换
     */
    public function exchange($data){

        if($this->logicApiBase->member['is_exchange']==0){
            return ajaxreturn(1,lang('获取最新币价失败,无法完成兑换'));
        }
        $uid=$this->logicApiBase->member['id'];
//        //        //验证支付密码
        $result=$this->check_password($data['pin_password']);
        switch ($result)
        {
            case 1:
                return  ajaxreturn(1,lang('您的账户操作多次密码验证不正确，如果不是您本人操作，请前往修改密码'));
                break;
            case 2:
                return  ajaxreturn(1,lang('您的密码验证错误2次，您的账户为了账户安全，已被冻结，请在30分钟后再次尝试。'));

                break;
            case 3:
                return  ajaxreturn(1,lang('您的密码验证错误1次，您还可以尝试1次！'));
                break;


        }
        if($data['form_wallet_id']==$data['to_wallet_id']){
            return ajaxreturn(1,lang('参数错误'));
        }
        if(empty($data['number'])){
            return ajaxreturn(1,lang('请输入数量'));
        }
        if(!is_numeric($data['number']) ){
            return ajaxreturn(1,lang('格式不正确'));
        }
        if($data['number']<0){
            return ajaxreturn(1,lang('数量不能为负数'));
        }
        if(!is_numeric($data['to_wallet_id']) ){
            return ajaxreturn(1,lang('格式不正确'));
        }

        if(!$form_wallet=Wallet::get([$data['form_wallet_id']])){
            return ajaxreturn(1,lang('币种错误'));
        }

        //是否开启兑换
        if($form_wallet['is_exchange']!=1){
            return ajaxreturn(1,lang('暂未开启'));
        }
        $exchange_min=(int)$form_wallet['exchange_min'];
        $exchange_max=(int)$form_wallet['exchange_max'];
        $exchange_daily_limit=(int)$form_wallet['exchange_daily_limit'];
        if($exchange_min>0){
            if($exchange_min>$data['number']){
                return ajaxreturn(1,lang('置换最小数量为').$exchange_min);
            }

        }
        if($exchange_max>0){
            if($exchange_max<$data['number']){
                return ajaxreturn(1,lang('置换最大数量为').$exchange_max);
            }

        }
        if(!empty($form_wallet['exchange_mult'])){
            if($data['number']%$form_wallet['exchange_mult']!=0){
                return ajaxreturn(1,lang('置换数量必须为').$form_wallet['exchange_mult'].lang('的倍数'));
            }

        }

        if($exchange_daily_limit>0){
            $total_money=UserAccountLog::where(['create_time'=>['between',[getTodayStart(),getTodayEnd()]],'user_id'=>$uid,'type'=>16,'wallet_id'=>$form_wallet['id'],'is_add'=>2])->sum('number')+0;

            if($total_money+$data['number']>$exchange_daily_limit){
                return ajaxreturn(1,lang('今日置换已达到上限'));
            }

        }
//       if($form_wallet['symbol']=='usdt'){
//            return ajaxreturn(1,lang('不支持置换'));
//        }
        if(!$wallet=Wallet::get([$data['to_wallet_id']])){
            return ajaxreturn(1,lang('币种错误'));
        }

        $poundage_number=$data['number']*$wallet['exchange_poundage']/100;
        Db::startTrans();
        $form=UserAccount::check(['user_id'=>$uid,'wallet_id'=>$data['form_wallet_id']],false);
        $to=UserAccount::check(['user_id'=>$uid,'wallet_id'=>$data['to_wallet_id']],false);
        $number_cc=($data['number']-$poundage_number)*$form->wallet->parities/$to->wallet->parities;

//        $total=$data['number']+$poundage;


        if($form['balance']<$data['number']){
            return ajaxreturn(1,lang('钱包余额不足'));
        }
        try{
            //账户余额扣除
            $form->balance-=$data['number'];
            $form->save();
            //写入资金流水
            UserAccountLog::create([
                'user_id'=>$uid,
                'number'=>$data['number'],
                'wallet_id'=>$form_wallet['id'],
                'before_blance'=> $form->balance+$data['number'],
                'poundage_number'=>$poundage_number,
                'after_blance'=> $form->balance,
                'is_add'=>2,
                'remark'=>' 置换'.' '.$wallet['name'].' '. $number_cc,
                'type'=>16
            ]);

            //主流币余额增加
            $to->balance+=$number_cc;
            $to->save();


            //写入资金流水
            UserAccountLog::create([
                'user_id'=>$uid,
                'number'=>$number_cc,
                'wallet_id'=>$wallet['id'],
                'before_blance'=>$to->balance-$number_cc,
                'poundage_number'=>$poundage_number,
                'after_blance'=> $to->balance,
                'is_add'=>1,
                'remark'=>$data['number'].' '.$form_wallet['name'].' 置换',
                'type'=>16
            ]);



            //写入转换记录
            $data['user_id']=$uid;
            $data['form_wallet_id']=$form_wallet['id'];
            $data['to_wallet_id']=$wallet['id'];
            $data['cc_number']=$number_cc;
            $data['remark']='1个'.$form_wallet['name'].'/'.$form_wallet['parities'].'￥,1个'.$wallet['name'].'/'.$wallet['parities'].'￥';
            $data['type']=19;
            $data['state']=1;
            $this->modelTransfer->setInfo($data);

            Db::commit();


        }catch( \Exception $e){
            Db::rollback();
            return ajaxreturn(1,$e->getMessage());
            return ajaxreturn(1,lang('服务器繁忙,请稍后再试'));
        }

        return ajaxreturn(0,lang('置换成功'));
    }

    /***
     * 法币转入总包
     */
    public function exchange_money($data){


        $uid=$this->logicApiBase->member['id'];
//        //        //验证支付密码
        $result=$this->check_password($data['pin_password']);
        switch ($result)
        {
            case 1:
                return  ajaxreturn(1,lang('您的账户操作多次密码验证不正确，如果不是您本人操作，请前往修改密码'));
                break;
            case 2:
                return  ajaxreturn(1,lang('您的密码验证错误2次，您的账户为了账户安全，已被冻结，请在30分钟后再次尝试。'));

                break;
            case 3:
                return  ajaxreturn(1,lang('您的密码验证错误1次，您还可以尝试1次！'));
                break;


        }

        if(empty($data['number'])){
            return ajaxreturn(1,lang('请输入数量'));
        }
        if(!is_numeric($data['number']) ){
            return ajaxreturn(1,lang('格式不正确'));
        }
        if($data['number']<0){
            return ajaxreturn(1,lang('数量不能为负数'));
        }
        if(!$form_wallet=Wallet::get([$data['form_wallet_id']])){
            return ajaxreturn(1,lang('币种错误'));
        }

        if(!empty($form_wallet['paddle_to_csj'])){
            if($form_wallet['paddle_to_csj']!=1){
                return ajaxreturn(1,lang('暂未开启'));
            }

        }
//       if($form_wallet['symbol']=='usdt'){
//            return ajaxreturn(1,lang('不支持置换'));
//        }
        if(!$wallet=Wallet::get(1)){
            return ajaxreturn(1,lang('币种错误'));
        }
        Db::startTrans();
        $form=EthAccount::where(['user_id'=>$uid])->lock(true)->find();
        $to=UserAccount::check(['user_id'=>$uid,'wallet_id'=>1],false);
        $number_cc=$data['number']*$form_wallet->parities;

//        $total=$data['number']+$poundage;

        $do=  $form_wallet['symbol'].'_do';
        if($form[ $do ]<$data['number']){
            return ajaxreturn(1,lang('钱包余额不足'));
        }
        try{
            //账户余额扣除
            $form->$do-=$data['number'];
            $form->save();
            //写入资金流水

            EthAccountLog::create([
                'user_id'=>$uid,
                'number'=>$data['number'],
                'wallet_id'=>$form_wallet['id'],
                'before_blance'=>$form->$do+$data['number'],
                'after_blance'=>$form->$do,
                'remark'=> '转入总包',
                'is_add'=>2,
                'type'=>5
            ]);

            //主流币余额增加
            $to->balance+=$number_cc;
            $to->save();


            //写入资金流水
            UserAccountLog::create([
                'user_id'=>$uid,
                'number'=>$number_cc,
                'wallet_id'=>$wallet['id'],
                'before_blance'=>$to->balance-$number_cc,
                'after_blance'=> $to->balance,
                'is_add'=>1,
                'remark'=>'法币转入',
                'type'=>16
            ]);



            //写入转换记录
            $data['user_id']=$uid;
            $data['form_wallet_id']=$form_wallet['id'];
            $data['to_wallet_id']=$wallet['id'];
            $data['cc_number']=$number_cc;
            $data['type']=22;
            $data['state']=1;
            $this->modelTransfer->setInfo($data);

            Db::commit();


        }catch( \Exception $e){
            Db::rollback();
            return ajaxreturn(1,$e->getMessage());
            return ajaxreturn(1,lang('服务器繁忙,请稍后再试'));
        }

        return ajaxreturn(0,lang('置换成功'));
    }


    /***
     * 总包转入法币
     */
    public function money_exchange_cyn($data){


        $uid=$this->logicApiBase->member['id'];
        $result=$this->check_password($data['pin_password']);
        switch ($result)
        {
            case 1:
                return  ajaxreturn(1,lang('您的账户操作多次密码验证不正确，如果不是您本人操作，请前往修改密码'));
                break;
            case 2:
                return  ajaxreturn(1,lang('您的密码验证错误2次，您的账户为了账户安全，已被冻结，请在30分钟后再次尝试。'));

                break;
            case 3:
                return  ajaxreturn(1,lang('您的密码验证错误1次，您还可以尝试1次！'));
                break;


        }

//        //        //验证支付密码
        if(empty($data['number'])){
            return ajaxreturn(1,lang('请输入数量'));
        }
        if(!is_numeric($data['number']) ){
            return ajaxreturn(1,lang('格式不正确'));
        }
        if($data['number']<0){
            return ajaxreturn(1,lang('数量不能为负数'));
        }
        if(!$to_wallet=Wallet::get([$data['to_wallet_id']])){
            return ajaxreturn(1,lang('币种错误'));
        }
//       if($form_wallet['symbol']=='usdt'){
//            return ajaxreturn(1,lang('不支持置换'));
//        }
        if(!$wallet=Wallet::get(1)){
            return ajaxreturn(1,lang('币种错误'));
        }
        if(!empty($form_wallet['paddle_to_exchange'])){
            if($form_wallet['paddle_to_exchange']!=1){
                return ajaxreturn(1,lang('暂未开启'));
            }

        }
        Db::startTrans();
        $to=EthAccount::where(['user_id'=>$uid])->lock(true)->find();
        $form=UserAccount::check(['user_id'=>$uid,'wallet_id'=>1],false);
        $number_cc=$data['number']/$to_wallet->parities;

//        $total=$data['number']+$poundage;

        $do=  $to_wallet['symbol'].'_do';
        if($form[ 'balance' ]<$data['number']){
            return ajaxreturn(1,lang('钱包余额不足'));
        }
        try{
            //账户余额扣除
            $form->balance-=$data['number'];
            $form->save();
            //写入资金流水
            UserAccountLog::create([
                'user_id'=>$uid,
                'number'=>$data['number'],
                'wallet_id'=>$wallet['id'],
                'before_blance'=>$form->balance+$data['number'] ,
                'after_blance'=> $form->balance,
                'is_add'=>2,
                'remark'=>'转入法币',
                'type'=>16
            ]);


            //主流币余额增加

            $to->$do+=$number_cc;
            $to->save();
            EthAccountLog::create([
                'user_id'=>$uid,
                'number'=>$number_cc,
                'wallet_id'=>$to_wallet['id'],
                'before_blance'=>$to->$do-$number_cc,
                'after_blance'=>$to->$do,
                'remark'=> '总包转入',
                'is_add'=>1,
                'type'=>6
            ]);




            //写入转换记录
            $data['user_id']=$uid;
            $data['form_wallet_id']=$wallet['id'];
            $data['to_wallet_id']=$to_wallet['id'];
            $data['cc_number']=$number_cc;
            $data['type']=22;
            $data['state']=1;
            $this->modelTransfer->setInfo($data);

            Db::commit();


        }catch( \Exception $e){
            Db::rollback();
            return ajaxreturn(1,$e->getMessage());
            return ajaxreturn(1,lang('服务器繁忙,请稍后再试'));
        }

        return ajaxreturn(0,lang('置换成功'));
    }

    /***
     * 钱包积分充值
     */
    public function wallet_recharge($data){


        $uid=$this->logicApiBase->member['id'];
        //        //验证支付密码
        $result=$this->check_password($data['pin_password']);
        switch ($result)
        {
            case 1:
                return  ajaxreturn(1,lang('您的账户操作多次密码验证不正确，如果不是您本人操作，请前往修改密码'));
                break;
            case 2:
                return  ajaxreturn(1,lang('您的密码验证错误2次，您的账户为了账户安全，已被冻结，请在30分钟后再次尝试。'));

                break;
            case 3:
                return  ajaxreturn(1,lang('您的密码验证错误1次，您还可以尝试1次！'));
                break;


        }

        if(empty($data['money'])){
            return ajaxreturn(1,lang('请输入数量'));
        }
        if(!is_numeric($data['money']) ){
            return ajaxreturn(1,lang('格式不正确'));
        }
        if($data['money']<0){
            return ajaxreturn(1,lang('数量不能为负数'));
        }
        if(!is_numeric($data['form_wallet_id']) ){
            return ajaxreturn(1,lang('格式不正确'));
        }

        if(!$form_wallet=Wallet::get([$data['form_wallet_id']])){
            return ajaxreturn(1,lang('币种错误'));
        }
//       if($form_wallet['symbol']=='usdt'){
//            return ajaxreturn(1,lang('不支持置换'));
//        }

        Db::startTrans();
        $form=UserAccount::check(['user_id'=>$uid,'wallet_id'=>$data['form_wallet_id']],false);
        $number_cc=$data['number'];

//        $total=$data['number']+$poundage;


        if($form['balance']<$number_cc){
            return ajaxreturn(1,lang('钱包余额不足'));
        }
        try{
            //账户余额扣除
            $form->balance-=$number_cc;
            $form->freeze_balance+=$number_cc;
            $form->save();

            //写入转换记录
            $data['user_id']=$uid;
            $data['form_wallet_id']=$form_wallet['id'];
            $data['type']=11;
            $data['state']=0;
            $this->modelTransfer->setInfo($data);

            Db::commit();


        }catch( \Exception $e){
            Db::rollback();
            return ajaxreturn(1,$e->getMessage());
            return ajaxreturn(1,lang('服务器繁忙,请稍后再试'));
        }

        return ajaxreturn(0,lang('提交充值成功,等待审核'));
    }



    /***
     * 数字资产提现
     */
    public function  withdrawal($data){
        if($this->logicApiBase->member['is_withdrawal']==0){
            return ajaxreturn(1,lang('您的网络异常,无法完成提币'));
        }
        $uid=$this->logicApiBase->member['id'];
        $member=$this->logicApiBase->member;
        $result=$this->check_password($data['pin_password']);
        switch ($result)
        {
            case 1:
                return  ajaxreturn(1,lang('您的账户操作多次密码验证不正确，如果不是您本人操作，请前往修改密码'));
                break;
            case 2:
                return  ajaxreturn(1,lang('您的密码验证错误2次，您的账户为了账户安全，已被冻结，请在30分钟后再次尝试。'));

                break;
            case 3:
                return  ajaxreturn(1,lang('您的密码验证错误1次，您还可以尝试1次！'));
                break;


        }
        if(empty($data['number'])){
            return ajaxreturn(1,lang('请输入数量'));
        }
        if(!is_numeric($data['number']) ){
            return ajaxreturn(1,lang('格式不正确'));
        }
        if($data['number']<0){
            return ajaxreturn(1,lang('数量不能为负数'));
        }
        if(!is_numeric($data['form_wallet_id']) ){
            return ajaxreturn(1,lang('格式不正确'));
        }
        if(!$wallet=Wallet::get([$data['form_wallet_id']])){
            return ajaxreturn(1,lang('币种错误'));
        }
        //提币是否开启
        if($wallet['is_withdrwal']!=1){
            return ajaxreturn(1,lang('服务尚未开启'));
        }
        
        //数量限制
        $withdrwal_min=(int)$wallet['withdrwal_min'];
        $withdrwal_max=(int)$wallet['withdrwal_max'];
        if($withdrwal_min>0){
            if($data['number']<$withdrwal_min) {
                return ajaxreturn(1, lang('数量最低为') .' '. $withdrwal_min);
            }
        }
        if($withdrwal_max>0){
            if($data['number']>$withdrwal_max) {
                return ajaxreturn(1, lang('数量最高为') .' '. $withdrwal_max);
            }
        }


        //倍数限制
        if($wallet['withdrwal_mult']>0){
            if($data['number']%$wallet['withdrwal_mult']!=0){
                return ajaxreturn(1,lang('数量必须为').$wallet['withdrwal_mult'].lang('的倍数'));
            }
        }
        //提现时间限制


        if($wallet['withdrwal_time']){
            $wallet_time_arr = explode("~",$wallet['withdrwal_time']);
            if(time()>strtotime($wallet_time_arr[1]) || time()<strtotime($wallet_time_arr[0])){
                return ajaxreturn(1,lang('提现时间限制为').$wallet['withdrwal_time']);
            }
        }
        if(!empty($data['email_type'])){
            if($data['email_type']==1){
                $user_sms_bean = $this->modelUserEmailLog->where(array('token' => $data['token'], 'email' => $this->logicApiBase->member['user_email'],'code'=>$data['code'], 'status' => 0))->find();
                if (empty($user_sms_bean)) {
                    return ajaxreturn(1, lang('验证码错误'));
    
                }
            }else{
                if(!$member['google_open']){
                    return ajaxreturn(1, lang('谷歌验证已关闭'));
                }else{
                    include_once(ROOT_PATH . 'extend/GoogleAuthenticator/PHPGangsta/GoogleAuthenticator.php');
                    $ga = new \PHPGangsta_GoogleAuthenticator();
                    $checkResult = $ga->verifyCode($this->logicApiBase->member['google_auth'], $data['code'], 1); 
                    if (!$checkResult) {
                        return ajaxreturn(1, lang('验证码错误'));
                    }
                }
            }
            
        }else{
            $data['area']=$this->logicApiBase->member['area'];
            $data['mobile']=$this->logicApiBase->member['mobile'];
            $res=$this->check_mobile_code($data);
            if(!$res){
                return ajaxreturn(1, lang('验证码错误'));
            }
        }



//        if($wallet['is_out']==2 ){
//            return ajaxreturn(1,lang('暂未开放该币种提现'));
//        }
        if(empty($data['to'])){
            return ajaxreturn(1,lang('请输入提币地址'));
        }
        Db::startTrans();
       $account= UserAccount::check(['user_id'=>$uid,'wallet_id'=>$wallet['id']],false);

        if($account['balance']<$data['number']){
            return ajaxreturn(1,lang('钱包余额不足'));
        }
        //游戏的业务流水为金额2倍不需要手续费
        if($data['number']*$wallet->parities*2>$this->logicApiBase->member['bets_total_balance']){
            $poundage=0;
            $data['poundage_remark']='本次提现因流水不足两倍需承担手续费';
        }else{
//            $withdrwal_poundage=Wallet::where(['id'=>1])->value('withdrwal_poundage');
            $poundage=$wallet['withdrwal_poundage']*$data['number']/100;
            $this->logicApiBase->member['bets_total_balance']-=$data['number']*$wallet->parities*2;
        }

        try{

            //账户余额扣除
            $account->balance-=$data['number'];
            $account->freeze_balance+=$data['number'];
            $account->save();

//            //写入资金流水
//            UserAccountLog::create([
//                'user_id'=>$uid,
//                'number'=>$data['number'],
//                'wallet_id'=>$wallet['id'],
//                'to_wallet_id'=>$wallet['id'],
//                'before_blance'=>$account->balance+$data['number'],
//                'after_blance'=>$account->balance,
//                'is_add'=>2,
//                'type'=>10
//            ]);


            //写入提币记录

            $data['from'] = $wallet['wallet_address2'];
            $data['user_id']=$uid;
            $data['form_wallet_id']=$wallet['id'];
            $data['poundage_number']=$poundage/100*$data['number'];
            $data['coin_number']=$data['number']-$data['poundage_number'];
            $data['type']=20;
            $data['money']=$data['number']*$wallet['parities'];
            $data['state']=0;
            $this->modelTransfer->setInfo($data);

            $mobile=getConfig('check_notice_mobile');
            $content= '您有一笔提币订单需正在审核中等待您处理';
            $data = [
                'mobile' =>$mobile,
                'content' => $content,
                'create_time' => TIME_NOW,
                'sms_type' => 30,
                'type' => 0,
                'area'=>86
            ];
            $sms=UserSms::create($data);

            if(getConfig('sms_is_test')!=1){
                $state=send_sms($mobile,$content ,config('settings'),86);
                if($state){
                    UserSms::where(['id'=>$sms->id])->update(['state'=>2]);
                }
            }
            Db::commit();


        }catch( \Exception $e){
            Db::rollback();
//            return ajaxreturn(0,$e->getMessage());
            return ajaxreturn(1,lang('服务器繁忙,请稍后再试'));
        }

        return ajaxreturn(0,lang('提币成功,等待审核'));
    }

    


    /***
     * 充币记录
     */
    public function recharge_log(){
        $member=$this->logicApiBase->member;
        $uid=$member['id'];
        $where['user_id']=$uid;
        $where['type']=10;
        $list=$this->modelTransfer->getList($where,'id,create_time,form_wallet_id,number,state','id desc');
        foreach ($list as $k=>$v){


            $list[$k]['wallet_name']=$v->wallet->data['name'];
            unset($v->wallet);



        }

        return $list;
    }

    /***
     * 提币记录
     */
    public function withwral_log(){
        $member=$this->logicApiBase->member;
        $uid=$member['id'];
        $where['user_id']=$uid;
        $where['type']=20;
        $list=$this->modelTransfer->getList($where,'id,create_time,form_wallet_id,number,poundage_number,state','id desc');
        foreach ($list as $k=>$v){


            $list[$k]['wallet_name']=$v->wallet->data['name'];
            $list[$k]['get_number']=format_money($v['number']-$v['poundage_number'],8);
            unset($v->wallet);



        }

        return $list;
    }

    /**
     * 余额明细
     */

    public function account_log($data){
        $member=$this->logicApiBase->member;
        $uid=$member['id'];
        $where['user_id']=$uid;
        $where['wallet_id']=$data['wallet_id'];
        $list=$this->modelUserAccountLog->getList($where,'id,serial_number,create_time,transfer_id,remark,is_add,number,wallet_id','id desc');
        foreach($list as $k=>$v){
            $list[$k]['state']=Db::name("transfer")->where(["id"=>$v["transfer_id"]])->find()["state"];
        }
        return $list;
    }





}
